package com.wac.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wac.blog.pojo.User;
import com.wac.blog.pojo.UserInfo;
import com.wac.blog.result.Result;
import com.wac.blog.service.UserInfoService;
import com.wac.blog.service.UserService;
import com.wac.blog.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    UserInfoService userInfoService;

    @GetMapping({"/toLogin","/login"})
    public String toLogin(){
        return "login";
    }

    @GetMapping({"/register"})
    public String toRegister(){
        return "register";
    }

    @GetMapping({"/","/index"})
    public String index(){
        return "index";
    }

    @PostMapping("/register")
    public String register(Model model, HttpServletRequest req){
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String repassword = req.getParameter("repassword");
        if (password.equals(repassword)){
            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
            if (user==null){
                User userSave = new User();
                userSave.setUid(Utils.getUuid());
                userSave.setRoleId(2);
                userSave.setGmtCreate(Utils.getTime());
                userSave.setLoginDate(Utils.getTime());
                userSave.setUsername(username);
                userSave.setPassword(new BCryptPasswordEncoder().encode(password)); //密码加密
                userService.save(userSave);
                userInfoService.save(new UserInfo().setUid(userSave.getUid()));
                return "redirect:/toLogin";
            }else {
                model.addAttribute("data",new Result(false,"用户名已存在",null));
                return "register";
            }
        }else {
            model.addAttribute("data",new Result(false,"密码确认有误",null));
            return "register";
        }
    }

}
